package com.mimiwang.oss.service.Imp;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.*;
import com.mimiwang.oss.config.OssConfiguration;
import com.mimiwang.oss.service.OssFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @AUTHOR:游李滨
 * @DATE:2022/10/2 20:58
 */
@Service
@Slf4j
public class OssFileServiceImp implements OssFileService {

    @Autowired
    @Qualifier("ossClient")
    private OSS ossClient;

    @Autowired
    OssConfiguration ossConfiguration;




    @Override
    public boolean createBucket(String bucketName) {

        try {
            // 创建存储空间。
            ossClient.createBucket(bucketName);
            return true;
        } catch (OSSException oe) {

            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
            return false;
        } catch (ClientException ce) {

            log.error("Error Message:" + ce.getMessage());
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

    /**
     *
     *              if (content != null) {
     *                 BufferedReader reader = new BufferedReader(new InputStreamReader(content));
     *                 while (true) {
     *                     String line = reader.readLine();
     *                     if (line == null) break;
     *                     System.out.println("\n" + line);
     *                 }
     *                 // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
     *                 content.close();
     *             }
     *
     *
     *
     * */
    @Override
    public InputStream downloadFile(String bucketName, String objectName) {

        try {

            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            return ossObject.getObjectContent();




        } catch (OSSException oe) {

            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {

            log.error("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return null;
    }

    @Override
    public String uploadFile(File file) {
        System.out.println(ossConfiguration.bucketName);
        return uploadFile(file,ossConfiguration.bucketName);
    }
    @Override
    public String uploadFile(String objectName, File file) {
        return uploadFile(file,ossConfiguration.bucketName,objectName);
    }

    @Override
    public String uploadFile(File file, String bucketName) {
        return  uploadFile(file,bucketName,ossConfiguration.defaultDir+"/"+UUID.randomUUID()+file.getName());
    }

    @Override
    public String uploadFile(File file, String bucketName, String objectName) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return uploadFile(fileInputStream,bucketName,objectName);

    }
    @Override
    public String uploadFile(String fileName,InputStream inputStream){
       return this.uploadFile(ossConfiguration.bucketName,inputStream,fileName);
    }
    @Override
    public String uploadFile(InputStream inputStream,String objectName) {

       return uploadFile(inputStream,ossConfiguration.bucketName, objectName);
    }
    @Override
    public String uploadFile(String bucket,InputStream inputStream, String fileName) {

        return uploadFile(inputStream,bucket, ossConfiguration.defaultDir+"/"+ UUID.randomUUID()+fileName);
    }

    @Override
    public String uploadFile(InputStream inputStream, String bucketName, String objectName) {
        try {



            ossClient.putObject(bucketName, objectName, inputStream,getObjectMetadata(objectName));
            return getUrl(bucketName,ossConfiguration.endpoint,objectName);
        } catch (OSSException oe) {

            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());

        } catch (ClientException ce) {

           log.error("Error Message:" + ce.getMessage());

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     *
     *     for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
     *                 System.out.println(" - " + objectSummary.getKey() + "  " +
     *                         "(size = " + objectSummary.getSize() + ")");
     *             }
     *
     *
     *
     * */
    @Override
    public ObjectListing list(String bucketName) {
        try {
            // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            // objectListing.getObjectSummaries获取所有文件的描述信息。
            return objectListing;
        } catch (OSSException oe) {

            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {

            log.error("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
    /**
     *
     *
     * */
    private ObjectMetadata getObjectMetadata(String objectName){
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(getContentType(objectName.substring(objectName.lastIndexOf("."))));
        return objectMetadata;
    }

    public String getUrl(String bucket,String endpoint,String objectName){

        return "https://"+bucket+"."+endpoint+"/"+objectName;
    }

    @Override
    public String getUrl(String objectName) {


        return getUrl(ossConfiguration.bucketName,ossConfiguration.endpoint,objectName);
    }

    @Override
    public Map<String, String> getSignature() {
        return getSignature(ossConfiguration.bucketName,ossConfiguration.defaultDir);
    }

    @Override
    public Map<String,String> getSignature(String bucketName,String dirName) {


        String accessId = ossConfiguration.accessKeyId;
        String accessKey = ossConfiguration.accessKeySecret;
        String endpoint = ossConfiguration.endpoint;

        String bucket = bucketName;
        // 填写Host地址，格式为https://bucketname.endpoint。
        String host = "https://"+bucketName+"."+endpoint;
        String dir = dirName+"/";

        Map<String, String> respMap=null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessId", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }
        return respMap;

    }

    private String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}
